<template>
    <div class="p-4">
        <t-card title="新闻管理" bordered>

            <!-- 顶部操作栏 -->
            <div class="mb-4 flex justify-between items-center">
                <t-input v-model="searchKeyword" placeholder="请输入新闻标题关键字" style="width: 300px" clearable @enter="fetchNewsList" />
                <div>
                    <t-button theme="primary" @click="openDialog('add')">新增新闻</t-button>
                </div>
            </div>

            <!-- 新闻表格 -->
            <t-table
                    row-key="id"
                    :data="newsList"
                    :columns="columns"
                    :loading="loading"
                    :pagination="pagination"
                    @page-change="onPageChange"
            >
                <!-- 状态列自定义（启用/禁用标签） -->
                <template #status="{ row }">
                    <t-tag :theme="row.status === 1 ? 'success' : 'danger'">
                        {{ row.status === 1 ? '启用' : '禁用' }}
                    </t-tag>
                </template>

                <!-- 操作列自定义（编辑/删除按钮） -->
                <template #operations="{ row }">
                    <t-button
                            size="small"
                            @click="onSubmit(row)"
                    >
                        编辑
                    </t-button>
                    <t-button
                            size="small"
                            theme="danger"
                            @click="deleteNews(row.id)"
                    >
                        删除
                    </t-button>
                </template>
            </t-table>

            <!-- 编辑弹窗 -->
            <t-dialog
                    v-model:visible="dialogVisible"
                    :header="dialogTitle"
                    width="600px"
                    :footer="false"
            >
                <t-form
                        ref="formRef"
                        :data="formData"
                        :rules="rules"
                        label-width="100px"
                        @submit.prevent="onSubmit"
                >
                    <t-form-item label="标题" name="title">
                        <t-input v-model="formData.title" clearable />
                    </t-form-item>

                    <t-form-item label="类型" name="type">
                        <t-input v-model="formData.type" clearable />
                    </t-form-item>

                    <t-form-item label="图片" name="image">
                        <t-input v-model="formData.image" clearable placeholder="图片URL" />
                    </t-form-item>

                    <t-form-item label="描述" name="description">
                        <t-textarea v-model="formData.description" rows="4" />
                    </t-form-item>

                    <t-form-item label="链接" name="link">
                        <t-input v-model="formData.link" clearable />
                    </t-form-item>

                    <t-form-item label="排序" name="sortOrder">
                        <t-input-number v-model="formData.sortOrder" :min="0" />
                    </t-form-item>

                    <t-form-item label="状态" name="status">
                        <t-radio-group v-model="formData.status">
                            <t-radio :value="1">启用</t-radio>
                            <t-radio :value="0">禁用</t-radio>
                        </t-radio-group>
                    </t-form-item>

                    <t-space align="center" class="mt-4">
                        <t-button theme="primary" @click="onSubmit">保存</t-button>
                        <t-button theme="default" variant="outline" @click="dialogVisible = false">取消</t-button>
                    </t-space>
                </t-form>
            </t-dialog>
        </t-card>
    </div>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import { MessagePlugin } from 'tdesign-vue-next';
    import newsApi from '../../api/news.js';

    const loading = ref(false);
    const searchKeyword = ref('');
    const newsList = ref([]);

    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const columns = [
        { colKey: 'id', title: 'ID', width: 80 },
        { colKey: 'title', title: '标题' },
        { colKey: 'type', title: '类型', width: 120 },
        { colKey: 'sortOrder', title: '排序', width: 100 },
        {
            colKey: 'status',
            title: '状态',
            width: 100
        },
        { colKey: 'createdAt', title: '创建时间', width: 180 },
        {
            title: '操作',
            colKey: 'operations', // 自定义插槽
            width: 140,
            fixed: 'right'
        },
    ];

    // 弹窗与表单
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增新闻');
    const formRef = ref(null);
    const formData = reactive({
        id: null,
        title: '',
        type: '',
        image: '',
        description: '',
        link: '',
        sortOrder: 0,
        status: 1,
    });

    const rules = {
        title: [{ required: true, message: '请输入标题' }],
    };

    // === 数据加载 ===
    const fetchNewsList = async () => {
        loading.value = true;
        try {
            const res = await newsApi.getNewsPage({
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
                keyword: searchKeyword.value,
            });
            newsList.value = res.data.records || res.data.list || [];
            pagination.total = res.data.total || 0;
        } catch (e) {
            MessagePlugin.error('获取新闻列表失败');
        } finally {
            loading.value = false;
        }
    };

    const onPageChange = (pageInfo) => {
        pagination.current = pageInfo.current;
        pagination.pageSize = pageInfo.pageSize;
        fetchNewsList();
    };

    // === 弹窗操作 ===
    const openDialog = (mode, row) => {
        if (mode === 'add') {
            dialogTitle.value = '新增新闻';
            Object.assign(formData, {
                id: null,
                title: '',
                type: '',
                image: '',
                description: '',
                link: '',
                sortOrder: 0,
                status: 1,
            });
        } else if (mode === 'edit' && row) {
            dialogTitle.value = '编辑新闻';
            Object.assign(formData, { ...row });
        }
        dialogVisible.value = true;
    };

    const onSubmit = async () => {
        try {
            await formRef.value.validate();
            if (formData.id) {
                await newsApi.updateNews(formData);
                MessagePlugin.success('更新成功');
            } else {
                await newsApi.addNews(formData);
                MessagePlugin.success('新增成功');
            }
            dialogVisible.value = false;
            fetchNewsList();
        } catch (e) {
            MessagePlugin.error('保存失败');
        }
    };

    // === 删除 ===
    const deleteNews = async (id) => {
        if (!confirm('确认删除该新闻吗？')) return;
        try {
            await newsApi.deleteNews(id);
            MessagePlugin.success('删除成功');
            fetchNewsList();
        } catch {
            MessagePlugin.error('删除失败');
        }
    };

    // 初始化
    onMounted(() => {
        fetchNewsList();
    });
</script>

<style scoped>
    .p-4 {
        padding: 16px;
    }
</style>
